package xiaozhi.modules.sys.init;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;

import lombok.extern.slf4j.Slf4j;

/**
 * 管理员用户初始化器
 * 在应用启动时初始化管理员用户
 */
@Component
@Slf4j
public class AdminUserInitializer implements ApplicationRunner {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Override
    public void run(ApplicationArguments args) throws Exception {
        try {
            // 检查是否已存在管理员用户
            Integer count = jdbcTemplate.queryForObject(
                "SELECT COUNT(*) FROM sys_user WHERE username = 'device666'", Integer.class);

            if (count == 0) {
                // 创建管理员用户
                jdbcTemplate.update(
                    "INSERT INTO sys_user (id, username, password, super_admin, status, create_date) " +
                    "VALUES (1947217363795050498, 'device666', '$2a$10$4KjVYb6y6t5eL8x5j0R3QeZ9c8B7vA6F5D4S3A2Q1W0E9R8T7Y6U', 1, 1, NOW())");

                // 为管理员用户分配角色
                jdbcTemplate.update(
                    "INSERT INTO sys_user_role (user_id, role_id) VALUES (1947217363795050498, 1)");

                log.info("管理员用户初始化成功: username=device666, password=Admin@123");
            } else {
                log.info("管理员用户已存在，跳过初始化");
            }
        } catch (Exception e) {
            log.error("管理员用户初始化失败: {}", e.getMessage());
        }
    }
}